
#include "Measurement.h"
#include <sstream>

extern const unsigned int BASE_UNIT_COEFFICIENT(1);

Measurement::Measurement(unsigned int amount, const Unit &unit)
:
amount(amount),
unit(unit)
{
}

bool Measurement::operator==(const Measurement &measurement) const throw(int)
{
    if(!unit.isInSameType(measurement.unit))
    {
        throw int(EXCEPTION_UNIT_TYPE_NOT_MATCH);
    }

    return getAmountInBaseUnit() == measurement.getAmountInBaseUnit();
}

bool Measurement::operator!=(const Measurement &measurement) const throw(int)
{
    return !(*this == measurement);
}

Measurement Measurement::operator+(const Measurement &measurement) const throw(int)
{
    if(!unit.isInSameType(measurement.unit))
    {
        throw int(EXCEPTION_UNIT_TYPE_NOT_MATCH);
    }

	unsigned int amount;
	if(unit <= measurement.unit)
	{	
		unsigned int factor = measurement.unit / unit;
		amount = this->amount + measurement.amount * factor;
		return Measurement(amount, this->unit);
	}
	else
	{
		unsigned int factor = unit / measurement.unit;
		amount = this->amount * factor + measurement.amount;
		return Measurement(amount, measurement.unit);
	}
}

unsigned int Measurement::getAmountInBaseUnit() const
{
    return unit.getValueInBaseUnit(amount);
}

string Measurement::formatToString() const
{
	return unit.formatToString(amount);
}

string Measurement::formatToStringInBaseUnit() const
{
    stringstream tmpStr;

    tmpStr << getAmountInBaseUnit() << " " << unit.getBaseUnitName();

    return tmpStr.str();
}


